#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <memory>
#include "InetAddr.hpp"
#include "Log.hpp"

// 模板方法模式
namespace socket_ns
{
    class Socket;
    const static int gbacklog = 8;
    using socket_sptr = std::shared_ptr<Socket>; // 共享指针，避免内存泄露

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR,
        USAGE_ERROR
    };

    class Socket
    {
    public:
        // 纯虚函数，基类本身不会提供函数的具体实现，由派生类来实现
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(InetAddr &addr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual socket_sptr Accepter(InetAddr *addr) = 0;

        virtual bool Connector(InetAddr &addr) = 0;
        virtual int SockFd() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;

    public:
        void BuildListenSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }

        bool BuildClientSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            return Connector(addr);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        // 实现
        TcpSocket(int fd = -1)
            : _sockfd(fd)
        {
        }
        void CreateSocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);

            // 创建失败
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket create error\n");
                exit(SOCKET_ERROR);
            }

            // 创建成功
            LOG(DEBUG, "socket create success, sockfd: %d\n", _sockfd);
        }
        void BindSocketOrDie(InetAddr &addr) override
        {
            // 为什么有了InetAddr 还要创建地址结构体
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));

            // 绑定失败
            if (n < 0)
            {
                LOG(FATAL, "socket bind error\n");
                exit(BIND_ERROR);
            }

            // 绑定成功
            LOG(DEBUG, "socket bind success, sockfd: %d\n", _sockfd);
        }

        void ListenSocketOrDie() override
        {
            int n = ::listen(_sockfd, gbacklog);

            // 监听失败
            if (n < 0)
            {
                LOG(FATAL, "socket listen error\n");
                exit(LISTEN_ERROR);
            }

            // 监听成功
            LOG(DEBUG, "listen success, sockfd: %d\n", _sockfd);
        }

        // addr 是输出型参数
        socket_sptr Accepter(InetAddr *addr) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);

            // 连接失败
            if (sockfd < 0)
            {
                LOG(WARNING, "socket accept error\n");
                return nullptr;
            }

            // 连接成功
            LOG(DEBUG, "socket accept success\n");
            *addr = peer;

            socket_sptr sock = std::make_shared<TcpSocket>(sockfd);
            return sock;
        }

        bool Connector(InetAddr &addr) override
        {
            // 为什么有了InetAddr 还要创建地址结构体

            // 目标主机的结构体
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));

            // 连接失败
            if (n < 0)
            {
                std::cerr << "connect error" << std::endl;
                return false;
            }

            // 连接成功
            return true;
        }
        int SockFd() override
        {
            return _sockfd;
        }

        // out 是输出型参数，仅接收报文，不能保证收到的报文是完整的
        int Recv(std::string *out) override
        {
            // 接收数据
            char inbuffer[1024];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer), 0);

            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }
        int Send(const std::string &in) override
        {
            int n=::send(_sockfd,in.c_str(),in.size(),0);

            return n;
        }

    private:
        int _sockfd;
    };

}